Given an integer array nums
, return true
if there exists a triple of indices(i, j, k)
such thati < j < k
andnums[i] < nums[j] < nums[k]
. If no such indices exists, return false
.
Input: nums = [1,2,3,4,5] Output: true Explanation: Any triplet where i < j < k is valid.
Input: nums = [5,4,3,2,1] Output: false Explanation: No triplet exists.
Input: nums = [2,1,5,0,4,6] Output: true Explanation: The triplet (3, 4, 5) is valid because nums[3] == 0 < nums[4] == 4 < nums[5] == 6.
1 <= nums.length <= 105
-231 <= nums[i] <= 231 - 1
Follow up: Could you implement a solution that runs in O(n)
time complexity and O(1)
space complexity?
# @param {Integer[]} nums# @return {Boolean}defincreasing_triplet(nums)min3=[nil,nil,nil]nums.eachdo |x| ifmin3[1].nil?min3[1]=xelsifmin3[2].nil? && x <= min3[1]min3[1]=xelsifmin3[2].nil?min3[2]=xelsifx > min3[2]returntrueelsifx > min3[1]min3[2]=xelsifmin3[0].nil? && x < min3[1]min3[0]=xelsif !min3[0].nil? && x > min3[0]min3=[nil,min3[0],x]elsif !min3[0].nil? && x < min3[0]min3[0]=xendendfalseend
implSolution{pubfnincreasing_triplet(nums:Vec<i32>) -> bool{letmut min3 = (None,None,None);for x in nums {match min3 {(_,None, _) => min3.1 = Some(x),(_,Some(b),None)if x < b => min3.1 = Some(x),(_,Some(b),None)if x > b => min3.2 = Some(x),(_,Some(b),Some(c))if x > c => returntrue,(_,Some(b),Some(c))if x > b => min3.2 = Some(x),(None,Some(b),Some(c))if x < b => min3.0 = Some(x),(Some(a),Some(b),Some(c))if x > a => min3 = (None,Some(a),Some(x)),(Some(a),Some(b),Some(c))if x < a => min3.0 = Some(x), _ => (),}}false}}